package com.dldata.devtools30.utils;

import com.dldata.devtools30.businessmodel.SessionUserInfoEntity;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.service.api.DevtApiMainEntityService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**工具类
 * Created by nijiwen on 2016/7/27.
 */
public  class Util {
    
    public static final String DEVTOOLUSER = "#devuser#";
    public static final String CURRENTTIME = "#currenttime#";
    public static final String REMOTEIP = "#remoteip#";
    

    /**
     * 替换sql固定参数
     * @param value
     * @param request
     * @return
     */
    public static String replaceDefault(String value,HttpServletRequest request){
        SessionUserInfoEntity userInfoEntity = RightUtil.getCurrentUser(request);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        value = value.replace(CURRENTTIME, formatter.format(new Date()));
        value = value.replace(DEVTOOLUSER, userInfoEntity.getDevtooluser());
        value = value.replace(REMOTEIP,NetUtil.getRemoteIp(request));
        return value;
    }
    /**
     * java 替换 ${xxx} 的内容
     * @param content
     * @param kvs
     * @return
     */
    public static String parse(String content,Map<String,String> kvs){
        Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
        Matcher m = p.matcher(content);
        StringBuffer sr = new StringBuffer();
        while(m.find()){
            String group = m.group();
            m.appendReplacement(sr, kvs.get(group));
        }
        m.appendTail(sr);
        return sr.toString();
    }

    /**
     * 非空判断
     * @param obj
     * @return
     */
    public static boolean checkNotNull(Object obj){
        if(obj!=null && !obj.equals("")){
            return true;
        }
        return false;
    }

    /**
     * 比较两个对象是否相同,不能比较数字吧
     * @param obj1
     * @param obj2
     * @return
     */
    public static boolean isEquals(Object obj1,Object obj2){
        if(Util.checkNotNull(obj1) && Util.checkNotNull(obj2) && !obj1.equals("") && !obj2.equals("")){
            if(obj1.equals(obj2)){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     *
     * @param isTrue        查询结果 true,successMsg y
     * @param falseMsg      失败提醒消息
     * @param successMsg        成功提醒消息
     * @return
     */
    public static String getCheckMeg(boolean isTrue,String successMsg,String falseMsg){
        // 验证框架需要两个key：info和status(y/n),y标识通过验证,n标识验证不通过
        return  "{\"info\":\"" + (isTrue ? successMsg : falseMsg) + "\",\"status\":\"" + (isTrue ? 'y' : 'n') + "\"}";
    }

    /**
     *
     * @param realPath      服务器真实地址
     * @param path2          要保存文件的文件夹路径
     * @param aftername     后缀名
     * @param request
     * @param f                要上传的文件
     * @param filesroad        存入数据库的字段名
     * @return
     */
    public static String saveFile(String realPath,String path2,String filename,String aftername,HttpServletRequest request,MultipartFile f,String filesroad){
        //复制
        try {
            File file1=new File(realPath+path2);
            if(!file1.exists()){
                file1.mkdirs();
            }
            //Long time=System.currentTimeMillis();
            //filesroad="Uploads"+path2+time+aftername;
            filesroad=path2+filename+aftername;
            //拷贝并且上传
            FileUtils.copyInputStreamToFile(f.getInputStream(), new File(realPath+path2, filename + aftername));
            return filesroad;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param realPath      服务器真实地址
     * @param path2          要保存文件的文件夹路径
     * @param aftername     后缀名
     * @param request
     * @param f                要上传的文件
     * @param filesroad        存入数据库的字段名
     * @return
     */
    public static String saveFile(String realPath,String path2,String filename,String aftername,HttpServletRequest request,File f,String filesroad){
        //复制
        FileInputStream fileInputStream =null;
        try {
            File file1=new File(realPath+path2);
            if(!file1.exists()){
                file1.mkdirs();
            }
            //Long time=System.currentTimeMillis();
            //filesroad="Uploads"+path2+time+aftername;
            filesroad=path2+filename+aftername;
            //拷贝并且上传
            fileInputStream = new FileInputStream(f);
            File destination = new File(realPath + path2, filename + aftername);
            logger.info(destination.getPath());
            System.out.println(destination.getPath());
            FileUtils.copyInputStreamToFile(fileInputStream, destination);
            return filesroad;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileInputStream!=null)
                fileInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("http_client_ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        // 如果是多级代理，那么取第一个ip为客户ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
        }

        if (isBoolIp(ip)) return ip;
        return "";
    }

    public static boolean isBoolIp(String ipAddress) {
        Pattern pattern = Pattern.compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    public static boolean isPhoneNumber(String phone) {
        String telRegex = "(^1[3|4|5|7|8][0-9]{9}$)";
        //String telRegex2 = "^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
        return phone.matches(telRegex);
    }

    public static String StrFormat(String rText) {
        if (rText.contains("$\'")) {
            return rText.replace("'", "''").replace("$\'", "");
        } else return rText;
    }
    
    public static <T> List<Map<String,Object>> getEnumMapNative(Class tClass)  {
//        ArrayList arrayList=new ArrayList(Arrays.asList(DbTableManager.FIELDTYPE.class));
        
        
        
        List<Map<String,Object>> maplist = new ArrayList<>();
        if(tClass.equals(EnumUtils.FIELDTYPE.class)){
            EnumUtils.FIELDTYPE[] values = EnumUtils.FIELDTYPE.values();
            for (int i = 0; i < values.length; i++) {
                EnumUtils.FIELDTYPE value = values[i];
                Map<String,Object> data=new HashMap<>();
                data.put("code",value.getCode());
                data.put("label",value.getLable());
                maplist.add(data);
            }
        }
        if(tClass.equals(EnumUtils.SEARCHLX.class)){
            EnumUtils.SEARCHLX[] values = EnumUtils.SEARCHLX.values();
            for (int i = 0; i < values.length; i++) {
                EnumUtils.SEARCHLX value = values[i];
                Map<String,Object> data=new HashMap<>();
                data.put("code",value.getValue());
                data.put("label",value.getLabel());
                maplist.add(data);
            }
        }
    
        if(tClass.equals(DevtApiMainEntityService.FunctionResultType.class)){
            DevtApiMainEntityService.FunctionResultType[] values = DevtApiMainEntityService.FunctionResultType.values();
            for (int i = 0; i < values.length; i++) {
                DevtApiMainEntityService.FunctionResultType value = values[i];
                Map<String,Object> data=new HashMap<>();
                data.put("code",value.getValue());
                data.put("label",value.getName());
                maplist.add(data);
            }
        }
        if(tClass.equals(DevtApiMainEntityService.FunctionType.class)){
            DevtApiMainEntityService.FunctionType[] values = DevtApiMainEntityService.FunctionType.values();
            for (int i = 0; i < values.length; i++) {
                DevtApiMainEntityService.FunctionType value = values[i];
                Map<String,Object> data=new HashMap<>();
                data.put("code",value.getValue());
                data.put("label",value.getName());
                maplist.add(data);
            }
        }
        
        return maplist;
    }

    //获取枚举键值对
    public static <T> List<Map<String,Object>> getEnumMap1(Class tClass,String ... argmethods )  {
        List<Map<String,Object>> maplist = new ArrayList<>();
        try {
            Object[] objects = tClass.getEnumConstants();
            String mc="getLable",code="getCode";
            if(argmethods!=null&&argmethods.length>=1){
                mc= StringUtil.isEmptyOrLength0(argmethods[0])? mc:argmethods[0];
            }
            if(argmethods!=null&&argmethods.length>=2){
                code= StringUtil.isEmptyOrLength0(argmethods[1])? code:argmethods[1];
            }
            //获取指定方法
            Method getLable = tClass.getMethod(mc);
            Method getCode = tClass.getMethod(code);
            for (Object obj : objects) {
                Map<String,Object> data=new HashMap<>();
                data.put("code",getCode.invoke(obj));
                data.put("label",getLable.invoke(obj));
                maplist.add(data);
            }

        }catch (Exception ex){
            throw new UnsupportedOperationException(ex.getMessage());
        }
        return maplist;
    }


    public static List startPage(List list, Integer pageNum,
                                 Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        if (list.size()<fromIndex){
            if (list.size()<pageSize){
                return list.subList(list.size()-1, list.size());
            }
            return list.subList(list.size()-1, pageSize);
        }

        List pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }

    public static final Logger logger = LoggerFactory.getLogger(Util.class);
    public static final Base64.Encoder WITHOUT_PADDING = Base64.getUrlEncoder();
    public static final Base64.Decoder DECODER = Base64.getUrlDecoder();
    public static final String jiamikey="tjdldata";
    public static final Charset CHARSET = Charset.forName("UTF-8");

//    public static void main(String[] args) {
////        System.out.println(JSON.toJSONString(invokeRemoteMethodV2("http://WINDOWS-MN3J113:8088/mockWebServiceInterfaceServiceSoapBinding",
////                "acceptMessage",
////                new Object[]{"123"})));
//
//        Map<String,String> m=new HashMap<>();
//        m.put("${a}","han");
//        m.put("${b}","zhong");
//        System.out.println( parse("例如有这样一个${a}字符串字符串：用户'${a}'的名称${b}", m));
//    }
}
